﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class BuildABTool : Editor //不会被打包
{
    //调用构建AB包方法
    [MenuItem("Tools/Build Windows Bundle")]
    static void BundleWindowsBuild()
    {
        BuildAB(BuildTarget.StandaloneWindows);
    }

    [MenuItem("Tools/Build Android Bundle")]
    static void BundleAndroidBuild()
    {
        BuildAB(BuildTarget.Android);
    }

    [MenuItem("Tools/Build iPhone Bundle")]
    static void BundleiPhoneBuild()
    {
        BuildAB(BuildTarget.iOS);
    }

    //查找存放AB包资源的文件
    //使用Unity提供的BuildPipeline进行构建，构建一个资源包   
    public static void BuildAB(BuildTarget _target)
    {
        //收集需要存放AB包资源的列表
        //AssetBundleBuild[] assetBundleBuilds = { };
        List<AssetBundleBuild> assetBundleBuilds = new List<AssetBundleBuild>();

        //处理依赖项文件，文件信息列表
        List<string> bundleInfos = new List<string>();



        string[] files = Directory.GetFiles(PathUtil.AssetPath + "/BundleResource", "*", SearchOption.AllDirectories); //查询这个路径下的所有文件夹目录
        for (int i = 0; i < files.Length; i++) 
        {
            //如果是后缀名是meta文件，跳过
            if (files[i].EndsWith(".meta", System.StringComparison.CurrentCulture))
            {
                continue;
            }
            //如果是后缀名是.DS_Store文件，MacOS的隐藏文件
            if (files[i].EndsWith(".DS_Store", System.StringComparison.CurrentCulture))
            {
                continue;
            }
            
            Debug.Log("file:"+files[i]);
            AssetBundleBuild assetBundleBuild = new AssetBundleBuild();
            
            //设置所有AB包的信息
            string assetName = PathUtil.GetUnityPath(files[i]); //获取到这个文件的相对路径
            Debug.Log("UnityPath:" + assetName);

            assetBundleBuild.assetNames = new string[] { assetName }; //AB包名字

            string bundleName = files[i].Replace(PathUtil.BundleResoucePath, "").ToLower(); //去掉前面的路径，只剩最后，并改成小写
            Debug.Log("BundleName:" + bundleName);

            assetBundleBuild.assetBundleName = bundleName + ".ab";

            //放进列表里
            assetBundleBuilds.Add(assetBundleBuild);

            //添加文件和依赖信息
            List<string> dependenceInfo = GetDependence(assetName); 
            string bundleInfo = assetName + "|" + bundleName + ".ab"; //通过 | 隔离 字段 

            if (dependenceInfo.Count > 0)
                bundleInfo = bundleInfo + "|" + string.Join("|", dependenceInfo); //Ab文件的相对路径信息 | AB包路径+名称 | 依赖项文件信息

            bundleInfos.Add(bundleInfo);
        }

        if (Directory.Exists(PathUtil.BundleOutPath))
            Directory.Delete(PathUtil.BundleOutPath,true); //先删除
        Directory.CreateDirectory(PathUtil.BundleOutPath); //再创建

        //构建资源包
        //streamingAssetsPath这个路径不一定有,先判断
        BuildPipeline.BuildAssetBundles(PathUtil.BundleOutPath,assetBundleBuilds.ToArray(),BuildAssetBundleOptions.None,_target);

        //写入依赖文件列表中
        File.WriteAllLines(PathUtil.BundleOutPath + "/" + AppConst.FileListName, bundleInfos); //使用类AppConst常量

        //刷新
        AssetDatabase.Refresh();
    }


    /// <summary>
    /// 获取依赖文件列表
    /// </summary>
    /// <param name="curFile"></param>
    /// <returns></returns>
    static List<string> GetDependence(string curFile)
    {
        List<string> dependence = new List<string>();
        string[] files = AssetDatabase.GetDependencies(curFile); //获取依赖项文件
        dependence = files.Where(file => !file.EndsWith(".cs") && !file.Equals(curFile)).ToList(); //脚本文件和自身文件剔除
        return dependence;
    }
}
